package com.aos.erp.fs.web;

import com.aos.erp.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;

@Slf4j
public class Base64MultipartFile implements MultipartFile {

    private ByteArrayInputStream byteArrayInputStream;
    private byte[] data = new byte[0];
    private String contentType = "Base64";

    public Base64MultipartFile(String str) throws BizException {
        if (str != null) {
            int length = str.length();
            //只取前面部分进行判断处理
            String temp = str.substring(0, length > 30 ? 30 : length);

            if (temp.startsWith("data:")) {
                int i = temp.indexOf(";");
                if (i > 0) {
                    contentType = temp.substring(5, i);
                }
            }

            //转换成byte存储
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                // Base64解码
                int i = temp.indexOf("base64,");
                if (i > 0) {
                    temp = str.substring(i + 7);
                }
                data = decoder.decodeBuffer(temp);
                byteArrayInputStream = new ByteArrayInputStream(data);
            } catch (Exception ex) {
                throw new BizException("文件保存失败");
            }
        }
    }

    @Override
    public String getName() {
        return "temp.Base64";
    }

    @Override
    public String getOriginalFilename() {
        return "temp.Base64";
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public long getSize() {
        return data.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return data;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return byteArrayInputStream;
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        if (byteArrayInputStream != null) {
            FileOutputStream outputStream = new FileOutputStream(dest);
            IOUtils.copy(byteArrayInputStream, outputStream);

            IOUtils.closeQuietly(byteArrayInputStream, outputStream);
        } else {
            log.error("文件不能为空");
        }

    }
}
